package com.zx.zxpicture.shared.websocket;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.zx.zxpicture.shared.auth.SpaceUserAuthManager;
import com.zx.zxpicture.shared.auth.model.SpaceUserPermissionConstant;
import com.zx.zxpicture.domain.picture.entity.Picture;
import com.zx.zxpicture.domain.space.entity.Space;
import com.zx.zxpicture.domain.user.entity.User;
import com.zx.zxpicture.domain.space.valueObject.SpaceTypeEnum;
import com.zx.zxpicture.application.service.PictureApplicationService;
import com.zx.zxpicture.application.service.SpaceApplicationService;
import com.zx.zxpicture.application.service.UserApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * ws连接请求拦截器
 */
@Slf4j
@Component
public class WsHandshakeInterceptor implements HandshakeInterceptor {
    @Resource
    private UserApplicationService userApplicationService;
    @Resource
    private PictureApplicationService pictureApplicationService;
    @Resource
    private SpaceApplicationService spaceApplicationService;
    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    //ws连接只服务于团队空间图片编辑，所以如果编辑的图片如果不是团队空间或者在团队空间中权限不够那么直接拒绝ws连接
    //添加功能：也适用于管理员 共享 编辑公共图库中的图片
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //转换为HttpServletRequest请求
        if(request instanceof ServletServerHttpRequest){
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
            //获取请求参数
            String pictureId = httpServletRequest.getParameter("pictureId");
            if(StrUtil.isBlank(pictureId)){
                log.error("缺少图片参数，拒绝ws连接");
                return false;
            }
            User loginUser = userApplicationService.getLoginUser(httpServletRequest);
            if(ObjUtil.isEmpty(loginUser)){
                log.error("用户未登录，拒绝ws连接");
                return false;
            }
            //校验用户是否有这个图片的权限
            Picture picture = pictureApplicationService.getById(pictureId);
            if(ObjUtil.isEmpty(picture)){
                log.error("图片不存在，拒绝ws连接");
                return false;
            }
            Long spaceId = picture.getSpaceId();
            Space space = null;
            if(spaceId != null){
                space = spaceApplicationService.getById(spaceId);
                if(ObjUtil.isEmpty(space)){
                    log.error("空间不存在，拒绝ws连接");
                }
                Integer spaceType = space.getSpaceType();
                if(!spaceType.equals(SpaceTypeEnum.TEAM.getValue())){
                    log.error("该图片不属于团队空间，拒绝ws连接");
                }
            }
            //查看权限
            List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
            if(!permissionList.contains(SpaceUserPermissionConstant.PICTURE_EDIT)){
                log.error("用户没有编辑权限，拒绝ws连接");
                return false;
            }
            //将用户信息存储到WebSocketSession中
            attributes.put("user",loginUser);
            attributes.put("userId",loginUser.getId());
            attributes.put("pictureId",Long.valueOf(pictureId));
            return true;
        }
        return false;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
